package com.fire.user.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fire.core.mode.TMitUserToken;
import com.fire.core.service.CkeckTokenService;
import com.fire.core.service.ITMitErrorCodeService;
import com.fire.core.service.RedisService;
import com.fire.core.util.AjaxResult;
import com.fire.core.util.BlogUtil;
import com.fire.core.util.CommonUtil;
import com.fire.core.util.Md5Util;
import com.fire.user.constants.ErrorCodeConstants;
import com.fire.user.dao.*;
import com.fire.user.model.*;
import com.fire.user.service.*;
import com.fire.user.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author MIT123
 * @since 2018-04-16
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UsersMapper, User> implements IUserService {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

	@Autowired
	RedisTemplate redisTemplate;
	@Autowired
	UsersMapper usersMapper;
	@Autowired
	UserWxMapper userWxMapper;
	@Autowired
	ITMitChannelService iTMitChannelService;
	@Autowired
	ITMitRecordLoginService iTMitRecordLoginService;
	@Autowired
	SmsCodeService sendSmsService;
	@Autowired
	IRecordSmsService iRecordSmsService;
	@Autowired
	ITMitErrorCodeService itMitErrorCodeService;
	@Autowired
	CkeckTokenService ckeckTokenService;
	@Autowired
	UserAuthorityMapper userAuthorityMapper;
	@Autowired
	FireProprietorUserMapper fireProprietorUserMapper;
	@Autowired
	FireSupervisorUserMapper fireSupervisorUserMapper;
	@Autowired
	FireMaintainUserMapper fireMaintainUserMapper;
	@Autowired
	SiteMapper siteMapper;

	@Autowired
	RedisService redisService;
	//验证码缓存时间 （秒）
	@Value("${outTime.cacheOverTime}")
	private long cacheOverTime;
	//短信时间（分钟）
	@Value("${outTime.smsOverTime}")
	private Integer smsOverTime;

	//验证码（静动态）
	@Value("${authCode.staticCode}")
	private Integer staticCode;

	//token失效时间
	@Value("${tokenOutTime.tokenTime}")
	private Integer tokenOutTime;

	/**
	 * 生成验证码
	 *
	 * @return
	 */
	@SuppressWarnings("unused")
	@Override
	public Map<String, Object> getVerifyode(String phone, String code) throws Exception {
		Map<String, Object> map = new HashMap<>(10);
		Map<String, Object> logMap=new HashMap<>(10);
		logMap.put("phone",phone);
		String json = JSONUtils.toJSONString(logMap);
		BlogUtil.inlog(json,phone,"mit/user/getVerifyode","getVerifyode()发送验证码","req");
		Integer num=0;
		if (null == code) {
			if(staticCode==1){
				num=111111;
				map.put("status", ErrorCodeConstants.SUCCESS);
				map.put("message", "短信验证码发送成功，操作有效期为"+cacheOverTime/60+"分钟");
				map.put("tips", "短信验证码发送成功，操作有效期为"+cacheOverTime/60+"分钟");
				map.put("code", "");
			}else {
				 num = (int) (Math.random() * (999999 - 100000 + 1)) + 100000;
				//短信接口
				AjaxResult ajaxResult = sendSmsService.sendSmsCode(phone, num.toString(), smsOverTime);
				if("0".equals(ajaxResult.getStatus())){
					map.put("status",ErrorCodeConstants.SUCCESS);
					map.put("message", "短信验证码发送成功，操作有效期为"+cacheOverTime/60+"分钟");
					map.put("tips", "短信验证码发送成功，操作有效期为"+cacheOverTime/60+"分钟");
					//记录短信发送记录
					sendSmsRecord(phone,0);
				}else{
					map.put("status","2066");
					map.put("message", "短信验证码发送失败");
					map.put("tips", "短信验证码发送失败");
					sendSmsRecord(phone,1);
				}
			}
			// 向redis里存入数据和设置缓存时间
			redisTemplate.opsForValue().set(phone, num.toString(), cacheOverTime, TimeUnit.SECONDS);
			json = JSONUtils.toJSONString(map);
			//BlogUtil.inlog(json,phone,"mit/user/getVerifyode","getVerifyode()发送验证码","resp");
		} else {
			// redis判断是否存在注册码和是否过期
			Long oldDate = redisTemplate.getExpire(phone);
			logMap=new HashMap(10);
			logMap.put("phone",phone);
			logMap.put("code",code);
			json = JSONUtils.toJSONString(logMap);
			BlogUtil.inlog(json,phone,"mit/user/getVerifyode","getVerifyode()验证验证码","req");
			if (oldDate > 0) {
				// 没有过期 验证验证码输入是否正确
				String oldCode = (String) redisTemplate.opsForValue().get(phone);
				if (!code.equals(oldCode)) {
					map.put("status", "2001");
					map.put("message", "短信验证码输入错误");
					map.put("tips", "[2001]短信验证码输入错误");
				} else {
					map.put("status", ErrorCodeConstants.SUCCESS);
					map.put("message", "短信验证通过");
					map.put("tips", "短信验证通过");
				}
			} else {
				map.put("status", "2001");
				map.put("message", "短信验证码错误");
				map.put("tips", "[2001]短信验证码错误");
				redisTemplate.delete(phone);
			}
		}
		String status = (String) map.get("status");
		String tips = itMitErrorCodeService.getTips(status);
		if(StringUtils.isNotBlank(tips)){
			LOGGER.info("替换后的tips:["+status+"]"+tips);
			map.put("tips",tips);
		}
		json = JSONUtils.toJSONString(map);
		BlogUtil.inlog(json,phone,"mit/user/getVerifyode","getVerifyode()验证验证码","resp");
		return map;
	}

	/**
	 * 添加用户
	 *
	 * @param users
	 */
	@Override
	public Map<String, Object> addUser(User users) throws Exception {
		Map<String, Object> map = new HashMap<>(10);
		User user=null;
		// 验证手机是否注册
		user= usersMapper.selectByPhone(users.getPhone());
		if (null==user) {
			if(null==users.getChannelid()) {
			users.setChannelid(1);
			}
			users.setCreatetime(new Date());
			// 如果是密码不为空
			if (null != users.getPasswd()) {
				// 密码加密
				String pwd = Md5Util.encrypt(users.getPasswd());
				users.setPasswd(pwd);
			}
			TMitChannel mitChannel = iTMitChannelService.selectById(users.getChannelid());
			if(null==users.getAliasname()) {
				/*users.setAliasname(mitChannel.getChannelname()+"_"+users.getPhone());*/
				users.setAliasname("ybt_"+users.getPhone());
			}
			if(null==users.getSex()){
				users.setSex(9);
			}
			Integer count = usersMapper.insert(users);
			//设置用户信息到缓存
			TMitUserToken userToken = setTokenRedis(users);
			//设置用户信息对应ID
			redisTemplate.opsForValue().set(users.getUserid().toString(), userToken.getToken(),tokenOutTime, TimeUnit.HOURS);
			//设置token缓存时间
			redisTemplate.opsForValue().set(userToken.getToken(), userToken,tokenOutTime, TimeUnit.HOURS);
			addRecordLogin(users,"verifyode");
			if (null != count) {
				map.put("status", ErrorCodeConstants.SUCCESS);
				map.put("message", "注册成功");
				map.put("tips", "注册成功");
				map.put("token", userToken.getToken());
				LOGGER.info("注册成功...........");

			}
		}else {
			map.put("status", "2019");
			map.put("message", "用户已存在");
			map.put("tips", "用户已存在");
		}
		String status = (String) map.get("status");
		String tips = itMitErrorCodeService.getTips(status);
		if(StringUtils.isNotBlank(tips)){
			LOGGER.info("替换后的tips:["+status+"]"+tips);
			map.put("tips",tips);
		}
		return map;
	}

	/**
	 * 用户登录
	 * @throws ParseException
	 */
	@Override
	public Map<String, Object> loginUser(User users) throws Exception {
		String json = JSON.toJSONString(users);
		BlogUtil.inlog(json,users.getPhone(),"mit/user/login","登陆","req");
		Map<String, Object> map = new HashMap<>(10);
		TMitUserToken userToken=null;
		User user=null;
		if(null==users.getChannelid()) {
			users.setChannelid(1);
		}
		 TMitChannel mitChannel = iTMitChannelService.selectById(users.getChannelid());
		  if(null!=mitChannel&&mitChannel.getChannelstatus()!=1) {
			  map.put("status", "2004");
			  map.put("message", "该渠道维护中，请联系客服人员！");
			  map.put("tips", "[2004]该渠道维护中，请联系客服人员！");
			  return map;
		  }
		// 如果是密码不为空,为密码登录
		if (null != users.getPasswd()) {
			// 密码加密
			String pwd = Md5Util.encrypt(users.getPasswd());
			users.setPasswd(pwd);
		}
		user=usersMapper.selectByPhone(users.getPhone());
		  if(null!=user){
			//手机存在，去验证是否登录过
				boolean flagUserId=redisService.exists(user.getUserid().toString());
				if (flagUserId) {
					//用户id是否超时
					Long oldDate = redisTemplate.getExpire(user.getUserid().toString(), TimeUnit.MINUTES);
					if (oldDate > 0) {
						String oldToken = (String) redisTemplate.opsForValue().get(user.getUserid().toString());
						userToken = ckeckTokenService.ckeckToken(oldToken);
						if (null != userToken) {
							//设置userId缓存时间
							redisTemplate.opsForValue().set(userToken.getUserid().toString(), userToken.getToken(), tokenOutTime, TimeUnit.HOURS);
							//更新token时间
							redisTemplate.opsForValue().set(userToken.getToken(), userToken, tokenOutTime, TimeUnit.HOURS);
						}
				}else{
						map.put("status", ErrorCodeConstants.TOKEN_OUT_TIME);
						map.put("message", "用户超时");
						map.put("tips", "["+ErrorCodeConstants.TOKEN_OUT_TIME+"]用户超时");
						return map;
				}
			}else{
					//用户未登录状态
					user = usersMapper.selectByUser(users);
					if (user == null) {
						map.put("status", "2003");
						map.put("message", "用户名或密码错误");
						map.put("tips", "[2003]用户名或密码错误");
						return map;
					} else {
						user.setChannelname(mitChannel.getChannelname());
						//设置用户信息到缓存
						userToken = setTokenRedis(user);
						//设置userId缓存时间
						redisTemplate.opsForValue().set(userToken.getUserid().toString(), userToken.getToken(), tokenOutTime, TimeUnit.HOURS);
						//设置token缓存时间
						redisTemplate.opsForValue().set(userToken.getToken(), userToken, tokenOutTime, TimeUnit.HOURS);
						user.setPasswd("");
					}

				}
		}else{
		  	/*addUser(users);
			  user = usersMapper.selectByUser(users);
			  user.setChannelname(mitChannel.getChannelname());
			  //设置用户信息到缓存
			  userToken = setTokenRedis(user);
			  //设置userId缓存时间
			  redisTemplate.opsForValue().set(userToken.getUserid().toString(), userToken.getToken(), tokenOutTime, TimeUnit.HOURS);
			  //设置token缓存时间
			  redisTemplate.opsForValue().set(userToken.getToken(), userToken, tokenOutTime, TimeUnit.HOURS);
			  user.setPasswd("");*/
			  map.put("status", ErrorCodeConstants.USER_ISNULL);
			  map.put("message", "用户不存在");
			  map.put("tips", "用户不存在");
			  return map;
		}
		addRecordLogin(user,"login");
		UserWx userWx = new UserWx();
		userWx.setUserid(user.getUserid());
		userWx = userWxMapper.selectOne(userWx);

		map.put("status", ErrorCodeConstants.SUCCESS);
		map.put("message", "登录成功");
		map.put("tips", "登录成功");
		map.put("token", userToken.getToken());
		map.put("aliasname", user.getAliasname());
		map.put("userid", user.getUserid());
		if(userWx != null){
			map.put("openid", userWx.getOpenid());
		}
		map.put("phone", user.getPhone());
		map.put("email", user.getEmail());
		map = getFireInformation(map,user.getUserid());
		LOGGER.info("登录成功..............");
		String status = (String) map.get("status");
		String tips = itMitErrorCodeService.getTips(status);
		if(StringUtils.isNotBlank(tips)){
			LOGGER.info("替换后的tips:["+status+"]"+tips);
			map.put("tips",tips);
		}
		 json = JSON.toJSONString(map);
		BlogUtil.inlog(json,user.getPhone(),"mit/user/login","登陆","resp");
		return map;
	}

	public Map getFireInformation(Map map,Integer userid){
		UserAuthorityModel userAuthorityModel = new UserAuthorityModel();
		userAuthorityModel.setUserid(userid);
		userAuthorityModel = userAuthorityMapper.selectOne(userAuthorityModel);
		String authority = userAuthorityModel.getAuthority();
		List<Map<String,String>> siteRes = null;
		switch (authority){
			case "proprietor":
				FireProprietorUserModel proprietorUserModel = new FireProprietorUserModel();
				proprietorUserModel.setUserid(userid);
				proprietorUserModel = fireProprietorUserMapper.selectOne(proprietorUserModel);
				String proprietor = proprietorUserModel.getProprietor();
				siteRes = siteMapper.selectListByProprietor(proprietor);
				break;
			case "supervisor":
				FireSupervisorUserModel fireSupervisorUserModel = new FireSupervisorUserModel();
				fireSupervisorUserModel.setUserid(userid);
				fireSupervisorUserModel = fireSupervisorUserMapper.selectOne(fireSupervisorUserModel);
				String supervisor = fireSupervisorUserModel.getSupervisor();
				siteRes = siteMapper.selectListBySupervisor(supervisor);
				break;
			case "maintainor":
				FireMaintainUserModel fireMaintainUserModel = new FireMaintainUserModel();
				fireMaintainUserModel.setUserid(userid);
				fireMaintainUserModel = fireMaintainUserMapper.selectOne(fireMaintainUserModel);
				String maintainor = fireMaintainUserModel.getMaintainor();
				siteRes = siteMapper.selectListByMaintainor(maintainor);
				break;
		}

		map.put("sitelist",siteRes);
		map.put("authority",authority);
		map.put("ismodifydevice",userAuthorityModel.getIsmodifydevice());
		map.put("ismodifyasset",userAuthorityModel.getIsmodifyaccet());
		map.put("ismodifysite",userAuthorityModel.getIsmodifysite());

		return map;
	}
	/**
	 * 获取用户个人信息
	 *
	 * @param json userid
	 *
	 */
	@Override
	public AjaxResult getuserInfo(String json) {
		AjaxResult ajaxResult = null;
		Map<String,Object> param = JSONObject.parseObject(json, Map.class);
		String token = null;
		Integer userid = null;
		try{
			token = (String)param.get("token");
			userid = (Integer)param.get("userid");
		}catch (Exception e) {
			return new AjaxResult(ErrorCodeConstants.USER_PARAMERROE,"请输入正确类型的参数","请输入正确类型的参数");
		}
		//参数校验
		if(StringUtils.isBlank(token) && null == userid) {
			LOGGER.info("传入的参数均为空");
			return new AjaxResult(ErrorCodeConstants.USER_PARAM_ISNULL,"输入参数","输入参数");
		}

		//若传入的token不为空则用token查询，否则用userid查询
		User user = new User();
		if (StringUtils.isNotBlank(token)) {
			TMitUserToken userToken = (TMitUserToken) redisTemplate.opsForValue().get(token);
			if(null != userToken) {
				userid = userToken.getUserid();
				BlogUtil.inlog(json,userid.toString(), "mit/user/getuserinfo", "/getuserinfo", "req");
				user = usersMapper.selectById(userToken.getUserid());
			}else {
				return new AjaxResult(ErrorCodeConstants.TOKEN_OUT_TIME,"用户信息无效","用户信息无效");
			}
		}else {
			BlogUtil.inlog(json, userid.toString(), "mit/user/getuserinfo", "/getuserinfo", "req");
			user = usersMapper.selectById(userid);
		}

		if (null == user) {
			LOGGER.info("数据库中不存在该用户信息");
			ajaxResult = new AjaxResult(ErrorCodeConstants.USER_ISNULL,"用户不存在","用户不存在");
	    	BlogUtil.inlog(JSONObject.toJSONString(ajaxResult), userid.toString(), "mit/user/getuserinfo", "/getuserinfo", "resp");
			return ajaxResult;
		}
		UserWx userWx = userWxMapper.selectById(user.getUserid());


		Map<String,Object> resp = new HashMap(10);
		resp.put("userid",user.getUserid());
		resp.put("aliasname",user.getAliasname());
		if(CommonUtil.isMobile(user.getPhone())) {
			resp.put("phone",user.getPhone());
		}else {
			resp.put("phone","");
		}
		resp.put("email",user.getEmail());
		resp.put("city",user.getCity());
		resp.put("sex",user.getSex());
		resp.put("avatar",user.getAvatar());
		resp = getFireInformation(resp,user.getUserid());

		if(null != userWx) {
			resp.put("openid",userWx.getOpenid());
		}else {
			resp.put("openid","");
		}
		resp.put("wxid",user.getWxid());
		ajaxResult = new AjaxResult(ErrorCodeConstants.SUCCESS, "获取成功", resp, "获取成功");
    	BlogUtil.inlog(JSONObject.toJSONString(ajaxResult), userid.toString(), "mit/user/getuserinfo", "/getuserinfo", "resp");
		return ajaxResult;
	}

	/**
	 * 个人用户设置
	 *
	 * @param json token avatar
	 *
	 */
	@Override
	@Transactional(rollbackFor=Exception.class)
	public AjaxResult usersetting(String json) {
		AjaxResult ajaxResult = null;
		Map<String,Object> param = JSONObject.parseObject(json, Map.class);
		Integer userid = null;
		String token = null;
		String avatar = null;
		String aliasname = null;
		String phone = null;
		String email = null;
		String sex = null;
		String city = null;
		try{
			userid = (Integer)param.get("userid");
			token = (String)param.get("token");
			avatar = (String)param.get("avatar");
			aliasname = (String)param.get("aliasname");
			phone = (String)param.get("phone");
			email = (String)param.get("email");
			sex = (String)param.get("sex");
			city = (String)param.get("city");
		}catch (Exception e) {
			LOGGER.error(e.getMessage());
			return new AjaxResult(ErrorCodeConstants.USER_PARAMERROE,"请输入正确类型的参数","请输入正确类型的参数");
		}
		//参数校验
		if(StringUtils.isBlank(token)) {
			return new AjaxResult(ErrorCodeConstants.USER_TOKEN_ISNULL,"token不能为空","token不能为空");
		}
		if(null == userid) {
			return new AjaxResult(ErrorCodeConstants.USER_USERID_ISNULL,"userid不能为空","userid不能为空");
		}
		if(StringUtils.isNotBlank(email)) {
			if(!CommonUtil.checkEmail(email) || email.length() > 32) {
				return new AjaxResult(ErrorCodeConstants.USER_EMAIL_ERROR,"邮件不合法","邮件不合法");
			}
		}
		if(StringUtils.isNotBlank(phone)) {
			if(!CommonUtil.isMobile(phone)) {
				return new AjaxResult(ErrorCodeConstants.USER_PHONE_ERROR,"手机号码不合法 ","手机号码不合法 ");
			}
		}
		if(StringUtils.isNotBlank(aliasname)) {
			if(aliasname.length() > 64) {
				return new AjaxResult(ErrorCodeConstants.USER_ALIASNAME_ERROR,"昵称长度不合法 ","昵称长度不合法 ");
			}
		}


		//验证token
		TMitUserToken userToken = (TMitUserToken) redisTemplate.opsForValue().get(token);
		if(null == userToken) {
			LOGGER.info("缓存中不存在该token");
			return new AjaxResult(ErrorCodeConstants.TOKEN_OUT_TIME,"用户信息无效","用户信息无效");
		}else {
			if(userid.intValue() != userToken.getUserid().intValue()) {
				return new AjaxResult(ErrorCodeConstants.USER_USERID_ERROR,"userid与token中的userid不一致","userid与token中的userid不一致");
			}
		}

    	BlogUtil.inlog(json, userid.toString(), "mit/user/usersetting", "/usersetting", "req");

		//更新用户信息
		Integer ret = null;
		User user = new User();
		user.setUserid(userid);
		user.setAliasname(aliasname);
		user.setPhone(phone);
		user.setEmail(email);
		if(StringUtils.isNotBlank(sex)) {
			user.setSex(Integer.parseInt(sex));
		}
		user.setCity(city);
		user.setUpdatetime(new Date());
		user.setAvatar(avatar);
		ret = usersMapper.updateById(user);
		if (ret == 0) {
			LOGGER.info("更新数据库失败");
			ajaxResult = new AjaxResult(ErrorCodeConstants.USER_MODIFY_FAIL, "修改失败","修改失败");
	    	BlogUtil.inlog(JSONObject.toJSONString(ajaxResult), userid.toString(), "mit/user/usersetting", "/usersetting", "resp");
			return ajaxResult;
		}
		user = usersMapper.selectById(userid);
		Map<String,Object> resp = new HashMap(10);
		resp.put("userid", user.getUserid());
		resp.put("aliasname", user.getAliasname());
		resp.put("password", user.getPasswd());
		if(CommonUtil.isMobile(user.getPhone())) {
			resp.put("phone", user.getPhone());
		}else {
			resp.put("phone", "");
		}
		resp.put("email", user.getEmail());
		resp.put("avatar", user.getAvatar());
		resp.put("sex", user.getSex());
		resp.put("city", user.getCity());
		ajaxResult = new AjaxResult(ErrorCodeConstants.SUCCESS, "修改成功",resp,"修改成功");
    	BlogUtil.inlog(JSONObject.toJSONString(ajaxResult), userid.toString(), "mit/user/usersetting", "/usersetting", "resp");
		return ajaxResult;
	}

	/**
	 * 修改密码
	 *
	 * @param json newpwd code
	 *
	 */
	@Override
	@Transactional(rollbackFor=Exception.class)
	public AjaxResult changePassword(String json) throws Exception {
		AjaxResult ajaxResult = null;
		Map<String,String> param = JSONObject.parseObject(json, Map.class);
		String phone = null;
		String newpwd = null;
		String code = null;
		try{
			phone = param.get("phone");
			newpwd = param.get("newpwd");
			code = param.get("code");
		}catch (Exception e) {
			return new AjaxResult(ErrorCodeConstants.USER_PARAMERROE,"请输入正确类型的参数","请输入正确类型的参数");
		}

		//校验参数
		if(StringUtils.isBlank(phone)) {
			return new AjaxResult(ErrorCodeConstants.USER_PARAM_ISNULL,"手机号码不能为空","手机号码不能为空");
		}
		if(!CommonUtil.isMobile(phone)) {
			return new AjaxResult(ErrorCodeConstants.USER_PHONE_ERROR,"手机号码不合法","手机号码不合法");
		}
		if(StringUtils.isBlank(newpwd)) {
			return new AjaxResult(ErrorCodeConstants.USER_PARAM_ISNULL,"新密码不能为空","新密码不能为空");
		}
		if(newpwd.length() > 32) {
			return new AjaxResult(ErrorCodeConstants.USER_PASSWORD_ERROR,"新密码长度不合法","新密码长度不合法");
		}
		if(StringUtils.isBlank(code)) {
			return new AjaxResult(ErrorCodeConstants.USER_PARAM_ISNULL,"手机验证码不能为空","手机验证码不能为空");
		}
		//输出日志
		BlogUtil.inlog(json, phone, "mit/user/chgpwd", "/chgpwd", "req");
		// 验证短信验证码
		Map<String, Object> verifyRes = this.getVerifyode(phone, code);
		String status = (String) verifyRes.get("status");
		String message = (String) verifyRes.get("message");
		String tips = (String) verifyRes.get("tips");
		if (!"0".equals(status)) {
			LOGGER.info("短信验证未通过");
			ajaxResult = new AjaxResult(status,message,tips);
	    	BlogUtil.inlog(JSONObject.toJSONString(ajaxResult), phone, "mit/user/chgpwd", "/chgpwd", "resp");
			return ajaxResult;
		}
		//设置新密码
		User user = new User();
		user.setPasswd(Md5Util.encrypt(newpwd));
		user.setUpdatetime(new Date());
		EntityWrapper<User> ew = new EntityWrapper<User>();
		ew.eq("phone", phone);
		Integer updateRet = usersMapper.update(user, ew);
		if (updateRet.intValue() == 0) {
			LOGGER.info("数据库更新失败");
			ajaxResult = new AjaxResult(ErrorCodeConstants.USER_MODIFY_FAIL,"密码修改失败","密码修改失败");
	    	BlogUtil.inlog(JSONObject.toJSONString(ajaxResult), phone, "mit/user/chgpwd", "/chgpwd", "resp");
			return ajaxResult;
		}

		ajaxResult = new AjaxResult(ErrorCodeConstants.SUCCESS,"密码修改成功","密码修改成功");
    	BlogUtil.inlog(JSONObject.toJSONString(ajaxResult), phone, "mit/user/chgpwd", "/chgpwd", "resp");
		return ajaxResult;
	}
	/**
	 * 用户退出
	 *
	 * @param json
	 */
	@Override
	public LoginOutResp logout(String json) {
		Map<String,String> param = JSONObject.parseObject(json, Map.class);
		BlogUtil.inlog(json, param.get("token"), "mit/user/logout", "logout", "req");
		if(StringUtils.isEmpty(param.get("token")) ){
			String tips=itMitErrorCodeService.getTips(ErrorCodeConstants.USER_PARAMERROE);
			if(StringUtils.isNotBlank(tips) ){
				return new LoginOutResp(ErrorCodeConstants.USER_PARAMERROE,"token不能为空",tips);
			}else{
				return new LoginOutResp(ErrorCodeConstants.USER_PARAMERROE,"token不能为空","["+ErrorCodeConstants.USER_PARAMERROE+"]"+"token不能为空");

			}
		}

		try {
			if (redisTemplate.hasKey(param.get("token"))) {
				long expiretime = redisTemplate.getExpire(param.get("token"));
				if (expiretime > 0) {
					TMitUserToken tMitUserToken= (TMitUserToken) redisTemplate.opsForValue().get(param.get("token"));
					String userId=tMitUserToken.getUserid().toString();
                    User user = usersMapper.selectById(userId);
                    addRecordLogin(user,"loginOut");

                    redisTemplate.delete(userId);
					redisTemplate.delete(param.get("token"));
					LOGGER.info("成功退出。。。");
					String tips=itMitErrorCodeService.getTips(ErrorCodeConstants.SUCCESS);
					if(StringUtils.isNotBlank(tips)){

						return new LoginOutResp(ErrorCodeConstants.SUCCESS,"成功退出",tips);
					}else{
						return new LoginOutResp(ErrorCodeConstants.SUCCESS,"成功退出","["+ErrorCodeConstants.SUCCESS+"]"+"成功退出");

					}
				}
			} else {
				LOGGER.info("缓存中的key不存在");
				String tips=itMitErrorCodeService.getTips(ErrorCodeConstants.TOKEN_OUT_TIME);
				if(StringUtils.isNotBlank(tips)){
				return new LoginOutResp(ErrorCodeConstants.TOKEN_OUT_TIME,"用户已经过期或者token不存在",tips);
				}else{
					return new LoginOutResp(ErrorCodeConstants.TOKEN_OUT_TIME,"用户已经过期或者token不存在","["+ErrorCodeConstants.TOKEN_OUT_TIME+"]"+"用户已经过期或者token不存在");

				}
				}
		} catch (Exception e) {
			LOGGER.error("redis出错", e);
			String tips=itMitErrorCodeService.getTips(ErrorCodeConstants.SYS_DATAERROE);
			if(StringUtils.isNotBlank(tips)){

				return new LoginOutResp(ErrorCodeConstants.SYS_DATAERROE,"redis数据库异常",tips);
			}else{

				return new LoginOutResp(ErrorCodeConstants.SYS_DATAERROE,"redis数据库异常","["+ErrorCodeConstants.SYS_DATAERROE+"]"+"redis数据库异常");
			}
		}
		return null;
	}

	/**
	 * 设置token缓存
	 * @param user
	 * @return
	 * @throws ParseException
	 */
	public TMitUserToken setTokenRedis(User user) throws ParseException {
		// 设置token
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); // 设置日期格式
		String date = df.format(new Date());
		String token = user.getUserid().toString() + date;
		token=Md5Util.encrypt(token);
		TMitUserToken userToken = new TMitUserToken();
		TMitChannel mitChannel = iTMitChannelService.selectById(user.getChannelid());
		userToken.setToken(token);
		userToken.setUserid(user.getUserid());
		userToken.setChannelid(user.getChannelid());
		userToken.setChannelname(mitChannel.getChannelname());
		userToken.setResourceid(user.getResourceid());
		userToken.setResourcename(user.getResourcename());
		userToken.setResourcetype(user.getResourcetype());
		userToken.setAliasname(user.getAliasname());
		userToken.setPhone(user.getPhone());
		if (!("").equals(user.getWxid()) || null != user.getUserid()) {
			userToken.setLogintype(1);
		} else {
			userToken.setLogintype(0);
		}
		userToken.setExpiretime(DateUtil.addDays(tokenOutTime/24));
		return userToken;
	}
	/**
	 * 记录登录信息
	 * @param users
	 *  name :注册  登录
	 */
	public void addRecordLogin(User users,String name) {
		TMitRecordLogin iMitRecordLogin=new TMitRecordLogin();
		iMitRecordLogin.setChanelid(users.getChannelid());
		iMitRecordLogin.setChanelname(users.getChannelname());
		iMitRecordLogin.setCreatetime(new Date());
		if(!"loginOut".equals(name)) {
			iMitRecordLogin.setLogintime(new Date());
		}
		if(null==users.getWxid()) {
		iMitRecordLogin.setLogintype("0");
		}else {
			iMitRecordLogin.setLogintype("1");
		}
		iMitRecordLogin.setUserid(users.getUserid().toString());
		iMitRecordLogin.setWho(users.getAliasname());
		iMitRecordLogin.setPhone(users.getPhone());
		iMitRecordLogin.setResourcetype(users.getResourcetype());
		iMitRecordLogin.setResourceid(users.getResourceid());
		if("verifyode".equals(name)){
			iMitRecordLogin.setWay(2);
		}else if("login".equals(name)){
			iMitRecordLogin.setWay(1);
		}else if("loginOut".equals(name)){
			iMitRecordLogin.setWay(0);
		}
		iTMitRecordLoginService.insert(iMitRecordLogin);
	}

	/**
	 * 新增用户
	 * @param user
	 * @return 用户ID
	 */
	@Override
	public void insertUser(User user) {
		usersMapper.insertUser(user);
	}

	//短信发送记录
	public void sendSmsRecord(String phone,Integer status){
		RecordSms recordSms=new RecordSms();
		recordSms.setContext("user模块发送验证码短信记录");
		recordSms.setCreatetime(new Date());
		recordSms.setPhone(phone);
		recordSms.setWho("fire-user");
		recordSms.setStatus(status);
		iRecordSmsService.insert(recordSms);
	}

}

